package com.sendpo.zjx.sendpo.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.gson.Gson;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.domain.UserPersonCenterDomain;
import com.sendpo.zjx.sendpo.domain.UserPlaceCenterDomain;
import com.sendpo.zjx.sendpo.net.HttpCode;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.table.User;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;
import com.sendpo.zjx.sendpo.views.MainScrollview;

import org.xutils.common.Callback;
import org.xutils.common.util.DensityUtil;
import org.xutils.ex.HttpException;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import ch.ielse.view.imagewatcher.ImageWatcher;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by Administrator on 2017/8/21.
 */

public class UserPersonCenterActivity extends AppCompatActivity implements ImageWatcher.OnPictureLongPressListener {

    @BindView(R.id.backbt)
    RelativeLayout backbt;
    @BindView(R.id.head)
    RelativeLayout head;
    @BindView(R.id.civ)
    CircleImageView civ;
    @BindView(R.id.fabu_bt)
    Button fabuBt;
    @BindView(R.id.tiezi_num)
    TextView tieziNum;
    @BindView(R.id.focus_num)
    TextView focusNum;


    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.uname)
    TextView uname;


    private LinearLayoutManager lm;
    @BindView(R.id.v_image_watcher)
    public ImageWatcher vImageWatcher;
    @BindView(value = R.id.maincrollview)
    MainScrollview maincrollview;
    private int id = 0;
    private RecylcerAdaper adpter;
    public int currentlastitem = 0;
    public boolean lastloading = false;
    private int pagenow=1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_center);
        Tools.initStatus(this, R.color.black);
        ButterKnife.bind(this);
        id = getIntent().getIntExtra("id", 0);
        initComponent();
        initUserplace("" + id);

    }

    private void initComponent() {
        List<User> userList = Xutils.queryAll(getApplication(), User.class);
        if (userList != null && userList.size() != 0) {
            if (userList.get(0).getUserId() == id) {
                fabuBt.setVisibility(View.VISIBLE);
            }
        }

        vImageWatcher.setTranslucentStatus(0); // 如果是透明状态栏，你需要给ImageWatcher标记 一个偏移值，以修正点击ImageView查看的启动动画的Y轴起点的不正确
        vImageWatcher.setErrorImageRes(R.mipmap.error_picture); // 配置error图标 如果不介意使用lib自带的图标，并不一定要调用这个API
        vImageWatcher.setOnPictureLongPressListener(this); // 长按图片的回调，你可以显示一个框继续提供一些复制，发送等功能
        lm = new LinearLayoutManager(this, OrientationHelper.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };

        recyclerview.setLayoutManager(lm);
        pagenow=1;
        query(pagenow,id);
        maincrollview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()){
                    case MotionEvent.ACTION_MOVE:
                        int scrollY=view.getScrollY();
                        int height=view.getHeight();
                        int scrollViewMeasuredHeight=maincrollview.getChildAt(0).getMeasuredHeight();
                        if(scrollY==0){
                            System.out.println("*******************滑动到了顶端 view.getScrollY()="+scrollY);
                        }
                        if((scrollY+height)==scrollViewMeasuredHeight){
                            if(adpter!=null&&adpter.dataBeen.size()>=6&&lastloading==false){
                                pagenow++;
                                  append(pagenow,id);
                            }

                        }
                        break;
                }
                return false;
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    @OnClick(value = {R.id.backbt, R.id.fabu_bt})
    public void OnMyClick(View view) {
        switch (view.getId()) {
            case R.id.backbt:
                finish();
                break;
            case R.id.fabu_bt:
                Intent star=new Intent(this, MyselfSubmitFabuActivity.class);
                startActivityForResult(star,2000);

                break;


        }
    }

    @Override
    public void onPictureLongPress(ImageView v, String url, int pos) {

    }

    public class RecylcerAdaper extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        public List<UserPersonCenterDomain.DataBean> dataBeen;
        public LayoutInflater inflater;

        public RecylcerAdaper(List<UserPersonCenterDomain.DataBean> dataBeen, Context context) {
            inflater = LayoutInflater.from(context);
            this.dataBeen = dataBeen;
        }
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            RecyclerView.ViewHolder ih = null;
            ih = new IndexHoler(inflater.inflate(R.layout.layout_genericuserguest_listitem, parent, false));
            return ih;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            final IndexHoler ih = (IndexHoler) holder;
           final UserPersonCenterDomain.DataBean dataBean=dataBeen.get(position);
            ih.civ.setImageResource(R.drawable.nim_avatar_default);
            Glide.with(UserPersonCenterActivity.this)
                    .load(""+dataBean.getUseravatar())
                    .asBitmap()
                    .animate(R.anim.fade_in)
                    .override(300, 300)
                    .centerCrop()
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                            ih.civ.setImageBitmap(resource);
                        }
                    });
            ih.uname.setText(""+dataBean.getUsername());
            ih.watchnum.setText(""+dataBean.getDynamicLooknumber());
            ih.datetime.setText(""+new SimpleDateFormat("yyyy年MM月dd日").format(Tools.getStringtoDate(dataBean.getDynamicCreatetime(),"yyyy-MM-dd HH:mm:ss")));
           ih.content.setText(""+dataBean.getDynamicComment());
            ih.all_ll.removeAllViews();
            List<String> imgs = dataBean.getImgs();
            if (imgs != null && imgs.size() != 0) {
                final List<String> ivs_s = new ArrayList<>();
                final List<ImageView> ivs = new ArrayList<>();
                for (String img : imgs) {
                    final ImageView iv = new ImageView(UserPersonCenterActivity.this);
                    iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
                    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(DensityUtil.dip2px(158), DensityUtil.dip2px(158));
                    lp.setMargins(DensityUtil.dip2px(10), 0, DensityUtil.dip2px(10), 0);
                    iv.setLayoutParams(lp);
                    iv.setBackgroundColor(getResources().getColor(R.color.default_lightgray));
                    Glide.with(UserPersonCenterActivity.this)
                            .load(img)
                            .asBitmap()
                            .animate(R.anim.fade_in)
                            .placeholder(getResources().getColor(R.color.default_lightgray))
                            .override(500, 500)
                            .into(iv);
                    iv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            vImageWatcher.show(iv, ivs, ivs_s);
                        }
                    });
                    ivs.add(iv);
                    ivs_s.add(img);
                    ih.all_ll.addView(iv);
                }
            }
            if(dataBean.isDynamicpraiseState()){
                ih.goods_iv.setImageResource(R.mipmap.yanchu_goodicon_focus);
            }else{
                ih.goods_iv.setImageResource(R.mipmap.yanchu_goodicon);

            }
            ih.goods_bt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                     List<User> userList= Xutils.queryAll(getApplication(),User.class);
                       if(userList==null||userList.size()==0){
                           Tools.redirectActivity(UserPersonCenterActivity.this,LoginActivity.class);
                           return;
                       }
                    if(dataBean.isDynamicpraiseState()){
                        ih.goods_iv.setImageResource(R.mipmap.yanchu_goodicon);
                        dataBean.setDynamicpraiseState(false);
                        int count=Integer.parseInt(ih.goood_tv.getText().toString().trim()+"");
                             count--;
                        ih.goood_tv.setText(count+"");
                        nofocus(userList.get(0).getUserId()+"",dataBean.getDynamicId()+"");
                    }else{
                        ih.goods_iv.setImageResource(R.mipmap.yanchu_goodicon_focus);
                        dataBean.setDynamicpraiseState(true);
                        int count=Integer.parseInt(ih.goood_tv.getText().toString().trim()+"");
                        count++;
                        ih.goood_tv.setText(count+"");
                        focus(userList.get(0).getUserId()+"",dataBean.getDynamicId()+"");
                    }
                }
            });
            ih.goood_tv.setText(""+dataBean.getDynamicPraiseCount());
                ih.guest_bt.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Map<String,Object> map=new HashMap<>();
                         map.put("data",dataBean);
                        Tools.redirectActivity(UserPersonCenterActivity.this,UserPersonCenterGuestActivity.class,map);
                    }
                });
            ih.watch_bt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Map<String,Object> map=new HashMap<>();
                    map.put("data",dataBean);
                    Tools.redirectActivity(UserPersonCenterActivity.this,UserPersonCenterGuestActivity.class,map);
                }
            });
            ih.rootView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Map<String,Object> map=new HashMap<>();
                    map.put("data",dataBean);
                    Tools.redirectActivity(UserPersonCenterActivity.this,UserPersonCenterGuestActivity.class,map);
                }
            });
           ih.all_ll.setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View view) {
                   Map<String,Object> map=new HashMap<>();
                   map.put("data",dataBean);
                   Tools.redirectActivity(UserPersonCenterActivity.this,UserPersonCenterGuestActivity.class,map);
               }
           });
            ih.guest_tv.setText(""+dataBean.getGuestcount());
             if(dataBean.getUsersex()==0){
                 ih.sex_rl.setBackgroundColor(getResources().getColor(R.color.default_blue));
                 ih.sex_iv.setImageResource(R.mipmap.sex_male_while);
             }else{
                 ih.sex_rl.setBackgroundColor(getResources().getColor(R.color.colorAccent));
                 ih.sex_iv.setImageResource(R.mipmap.sex_female_while);
             }
             ih.sex_tv.setText(""+dataBean.getUserage());

        }

        @Override
        public int getItemCount() {
            return dataBeen.size();
        }

        public class IndexHoler extends RecyclerView.ViewHolder {
            public View rootView;
            public LinearLayout all_ll;
            public CircleImageView civ;
         public TextView uname;
            public TextView datetime;
            public TextView watchnum;
            public ImageView goods_iv;
            public TextView content;
         public RelativeLayout goods_bt;
            public TextView goood_tv;
            public RelativeLayout guest_bt;
            public RelativeLayout watch_bt;
            public TextView guest_tv;

            public RelativeLayout sex_rl;
            public ImageView sex_iv;
            public TextView sex_tv;
            public TextView location_tv;
            public IndexHoler(View itemView) {
                super(itemView);
                rootView = itemView;
                all_ll = itemView.findViewById(R.id.all_ll);
                civ = itemView.findViewById(R.id.cir_icon);
                uname=itemView.findViewById(R.id.uname);
                datetime=itemView.findViewById(R.id.datetime);
                watchnum=itemView.findViewById(R.id.watchnum);
                goods_iv= itemView.findViewById(R.id.goods_iv);
                content=itemView.findViewById(R.id.content);
                goods_bt=itemView.findViewById(R.id.goods_bt);
                goood_tv=itemView.findViewById(R.id.goood_tv);
                guest_bt=itemView.findViewById(R.id.guest_bt);
                watch_bt=itemView.findViewById(R.id.watch_bt);
                guest_tv=itemView.findViewById(R.id.guest_tv);
                sex_rl=itemView.findViewById(R.id.sex_rl);
                sex_iv=itemView.findViewById(R.id.sex_iv);
                sex_tv=itemView.findViewById(R.id.sex_tv);
                location_tv=itemView.findViewById(R.id.location_tv);
            }
        }

        public void initRefresh(List<UserPersonCenterDomain.DataBean> domains) {
            this.dataBeen.removeAll(this.dataBeen);
            this.dataBeen.addAll(domains);
            notifyDataSetChanged();
        }

        public void initAppend(List<UserPersonCenterDomain.DataBean> domains) {
            this.dataBeen.addAll(domains);
            notifyDataSetChanged();
        }

        public void delete(int position) {
            this.dataBeen.remove(position);
            notifyDataSetChanged();
        }

       public  void focus(String userId,String dynamicId){
            Map<String,String> map=new HashMap<>();
            map.put("userId",""+userId);
            map.put("dynamicId",dynamicId);
            Xutils.POST(HttpUrl.userdynamicpraiseAdd, map, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {

                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });

        }
        public  void  nofocus(String userId,String dynamicId){
            Map<String,String> map=new HashMap<>();
            map.put("userId",""+userId);
            map.put("dynamicId",dynamicId);
            Xutils.POST(HttpUrl.userdynamicpraiseDelete, map, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {

                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });

        }
    }

    public void query(int pagenow, final int userId) {
        Map<String, String> map = new HashMap<>();
        map.put("pagenow", pagenow + "");
        map.put("userId", userId + "");
        Xutils.POST(HttpUrl.dynamicById, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                UserPersonCenterDomain domain = gson.fromJson(result, UserPersonCenterDomain.class);
                switch (domain.getState()) {
                    case HttpCode.SUCCESS:
                        if (domain.getData() != null && domain.getData().size() != 0) {
                            if (adpter == null) {
                                recyclerview.setAdapter(adpter = new RecylcerAdaper(domain.getData(), UserPersonCenterActivity.this));
                                recyclerview.setOnScrollListener(new RecyclerView.OnScrollListener() {
                                    @Override
                                    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                                        super.onScrollStateChanged(recyclerView, newState);
                                        if (currentlastitem == lm.getItemCount() - 1 && newState == RecyclerView.SCROLL_STATE_IDLE) {
                                            if (UserPersonCenterActivity.this.pagenow == 1 && adpter.dataBeen.size() >= 10 && lastloading == false) {
                                                UserPersonCenterActivity.this.pagenow++;
                                                append(UserPersonCenterActivity.this.pagenow, userId);
                                            }
                                        }
                                    }

                                    @Override
                                    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                                        super.onScrolled(recyclerView, dx, dy);
                                        currentlastitem = lm.findLastVisibleItemPosition();
                                    }
                                });
                            } else {
                                adpter.initRefresh(domain.getData());
                            }

                        }
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public void append(int pagenow, final int userId) {
        lastloading = true;
        Map<String, String> map = new HashMap<>();
        map.put("pagenow", pagenow + "");
        map.put("userId", userId + "");
        Xutils.POST(HttpUrl.dynamicById, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                lastloading = false;
                Gson gson = new Gson();
                UserPersonCenterDomain domain = gson.fromJson(result, UserPersonCenterDomain.class);
                switch (domain.getState()) {
                    case HttpCode.SUCCESS:
                        if (domain.getData() != null && domain.getData().size() != 0) {
                            if (adpter == null) {
                                recyclerview.setAdapter(adpter = new RecylcerAdaper(domain.getData(), UserPersonCenterActivity.this));
                                recyclerview.setOnScrollListener(new RecyclerView.OnScrollListener() {
                                    @Override
                                    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                                        super.onScrollStateChanged(recyclerView, newState);
                                        if (currentlastitem == lm.getItemCount() - 1 && newState == RecyclerView.SCROLL_STATE_IDLE) {
                                            if (UserPersonCenterActivity.this.pagenow == 1 && adpter.dataBeen.size() >= 10 && lastloading == false) {
                                                UserPersonCenterActivity.this.pagenow++;
                                                append(UserPersonCenterActivity.this.pagenow, userId);
                                            }
                                        }
                                    }

                                    @Override
                                    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                                        super.onScrolled(recyclerView, dx, dy);
                                        currentlastitem = lm.findLastVisibleItemPosition();
                                    }
                                });
                            } else {
                                adpter.initAppend(domain.getData());
                            }

                        }
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                lastloading = false;
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }




    public void initUserplace(String userid) {
        Map<String, String> map = new HashMap<>();
        map.put("userId", userid);
        Xutils.POST(HttpUrl.dynamicgetplaceinfobyuserId, map, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                UserPlaceCenterDomain domain = gson.fromJson(result, UserPlaceCenterDomain.class);
                switch (domain.getState()) {
                    case HttpCode.SUCCESS:
                        if (domain.getData() != null) {
                            List<User> userList = Xutils.queryAll(getApplication(), User.class);
                            if (userList != null && userList.size() != 0) {
                                if (userList.get(0).getUserId() == id) {
                                    title.setText("我的空间");
                                } else {
                                    title.setText("" + domain.getData().getUserName());
                                }
                            } else {
                                title.setText("" + domain.getData().getUserName());
                            }
                            Glide.with(UserPersonCenterActivity.this)
                                    .load("" + domain.getData().getUserAvatarpath())
                                    .asBitmap()
                                    .placeholder(R.drawable.nim_avatar_default)
                                    .override(300, 300)
                                    .centerCrop()
                                    .animate(R.anim.fade_in)
                                    .into(new SimpleTarget<Bitmap>() {
                                        @Override
                                        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                            civ.setImageBitmap(resource);
                                        }
                                    });
                            uname.setText("" + domain.getData().getUserName());
                        }
                   tieziNum.setText(""+domain.getData().getCount());
                        focusNum.setText(""+domain.getData().getWatchcount());
                        break;
                    case HttpCode.ERROR:

                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                if (ex instanceof HttpException) {
                    Toast.makeText(getApplicationContext(), "网络连接有误", Toast.LENGTH_SHORT).show();
                } else {

                }
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
             if(resultCode!=RESULT_OK){
                 return;
             }
         switch (requestCode){
             case 2000:
                  pagenow=1;
                query(pagenow,id);
                 break;

         }
    }
}
